<script setup>
import doctorsApi from '@/api/doctorsApi';
import {reactive, ref, toRaw} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import service from '@/api';
import {Plus, Search} from "@element-plus/icons-vue";
import adminApi from "@/api/adminApi";
import {tokenStore} from "@/store";
const doctors = ref([]);
// 获取 token store 实例
const tokenStoreInstance = tokenStore()
// 获取 token 值
const token = tokenStoreInstance.token
// 分页信息
const pageInfo = reactive({
  page: 1,
  limit: 5,
  total: 0,
  name: '',
  phone: '',

})

// 获取医生列表
loadDoctors();

// 页码和页面大小更新
function loadDoctors() {
  doctorsApi.search(pageInfo).then(result => {
    doctors.value = result.records;
    console.log(doctors.value);
    pageInfo.total = result.total;
    pageInfo.page = result.current;
    pageInfo.limit = result.size;
  });
}

// 添加的相关操作
const addVisible = ref(false);

const addDoctor = ref({});

function showAdd() {
  addVisible.value = true;    // 显示添加窗口
}

function handleAdd() {
  doctorsApi.add(addDoctor.value).then(result => {
    // console.log(result);
    if (result.code == 200) {
      ElMessage({message: '添加成功！', type: 'success'})
      addVisible.value = false;
      addDoctor.value = {};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadDoctors();
  });
}

// 编辑的操作
const editVisible = ref(false);

const editDoctor = ref({});

function showEdit(row) {
  editVisible.value = true;
  editDoctor.value = JSON.parse(JSON.stringify(row));   // 深拷贝
  editDoctor.value.password = "";
}


function handleEdit() {
  // console.log(editDoctor.value)
  const doctorData = toRaw(editDoctor.value);
  delete editDoctor.value.createTime;
  delete editDoctor.value.updateTime;
  console.log(doctorData)
  doctorsApi.edit(doctorData).then(result => {
    if (result.code == 200) {
      ElMessage({message: '编辑医生成功！', type: 'success'})
      editVisible.value = false;
      editDoctor.value = {};
    } else {
      ElMessage.error(result.data);
    }
    // 刷新表格数据
    loadDoctors();
  });
}

//删除一个医生
function handleRemove(doctor) {
  ElMessageBox.confirm(
      '亲，确定要开除当前医生么?',
      '警告',
      {
        confirmButtonText: '开除',
        cancelButtonText: '我再想想',
        type: 'warning',
      }
  ).then(() => {
    // 确定
    doctorsApi.remove(doctor.id).then(result => {
      if (result.code == 200) {
        ElMessage({message: '移除医生成功！', type: 'success'})
      } else {
        ElMessage.error(result.data);
      }
      // 刷新表格数据
      loadDoctors();
    });
  });

}

function handleAddAvatarSuccess(response, uploadFile) {
  addDoctor.value.photo = response.data;
}
//修改头像
function handleEditAvatarSuccess(response, uploadFile) {
  editDoctor.value.photo = response.data;
}

//获得图片的URL
function getImgUrl(url) {
  return url;
}

function getUploadURL() {
  return  '/api/upload';
}

function onSearch() {
  pageInfo.page = 1;
  loadDoctors();
}

const rules=ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
  ]
})
</script>

<template>
  <div class="content">
    <el-form :model="pageInfo" :inline="true">
      <el-form-item label="姓名" :label-width="60">
        <el-input v-model="pageInfo.name" clearable placeholder="请输入医生姓名" style="width: 200px"/>
      </el-form-item>
      <el-form-item label="手机号" :label-width="60">
        <el-input v-model="pageInfo.phone" clearable placeholder="请输入医生的手机号" style="width: 200px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">
          <el-icon>
            <Search></Search>
          </el-icon>
        </el-button>
      </el-form-item>
    </el-form>

    <div class="bar">
      <el-button type="success" @click="showAdd">添加医生</el-button>
    </div>
    <el-table :data="doctors" :stripe="true" :border="true" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="photo" label="照片">
        <template #default="scope">
          <img
              :src="getImgUrl(scope.row.photo)"
              class="circular-photo"
              alt=""/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名"/>
      <el-table-column prop="gender" label="性别">
        <template #default="scope">
          {{ scope.row.gender === 'M' ? '男' : scope.row.gender === 'F' ? '女' : '未知' }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="180"/>
      <el-table-column prop="email" label="邮箱"/>
      <el-table-column prop="recomm" label="擅长领域"></el-table-column>


      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" type="success"
                     @click="showEdit(scope.row)">编辑
          </el-button>
          <el-button size="small" type="danger"
                     @click="handleRemove(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page" v-model:current-page="pageInfo.page" v-model:page-size="pageInfo.limit"
                   :total="pageInfo.total" :page-sizes="[5, 7, 10, 20]" :background="true"
                   layout="total, sizes, prev, pager, next, jumper" @change="loadDoctors"/>
  </div>

  <!-- 添加的弹窗 -->
  <el-dialog v-model="addVisible" title="添加新医生" width="500">
    <el-form :model="addDoctor" :rules="rules">
      <el-form-item label="照片" :label-width="60">
        <el-upload
            class="avatar-uploader"
            :action="getUploadURL()"
            :show-file-list="false"
            :headers="{'token': token}"
            :on-success="handleAddAvatarSuccess"
        >
          <img v-if="addDoctor.photo" :src="getImgUrl(addDoctor.photo)" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名字" :label-width="60" prop="name">
        <el-input v-model="addDoctor.name" placeholder="请输入医生名字"/>
      </el-form-item>
      <el-form-item label="性别" :label-width="60">
        <el-radio-group v-model="addDoctor.gender">
          <el-radio label="M">男</el-radio>
          <el-radio label="F">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电话" :label-width="60" prop="phone">
        <el-input v-model="addDoctor.phone" placeholder="请输入医生电话"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="60">
        <el-input v-model="addDoctor.email" placeholder="请输入医生邮箱"/>
      </el-form-item>

      <el-form-item label="简介" :label-width="60">
        <el-input
            :rows="5"
            maxlength="255"
            placeholder="请输入医生简介"
            show-word-limit
            type="textarea"
            v-model="addDoctor.recomm"
            autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">
          创建
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑的弹窗 -->
  <el-dialog v-model="editVisible" title="编辑医生" width="500">
    <el-form :model="editDoctor">
      <el-form-item label="照片" :label-width="60">
        <el-upload
            class="avatar-uploader"
            :action="getUploadURL()"
            :show-file-list="false"
            :headers="{'token': token}"
            :on-success="handleEditAvatarSuccess"
        >
          <img v-if="editDoctor.photo" :src="getImgUrl(editDoctor.photo)" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名字" :label-width="60">
        <el-input v-model="editDoctor.name" placeholder="请输入医生名字"/>
      </el-form-item>
      <el-form-item label="性别" :label-width="60">
        <el-radio-group v-model="editDoctor.gender">
          <el-radio label="M">男</el-radio>
          <el-radio label="F">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="电话" :label-width="60">
        <el-input v-model="editDoctor.phone" placeholder="请输入医生的手机号"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="60">
        <el-input v-model="editDoctor.email" placeholder="请输入医生的邮箱"/>
      </el-form-item>
      <el-form-item label="简介" :label-width="60">
        <el-input
            :rows="5"
            maxlength="255"
            placeholder="请输入医生简介"
            show-word-limit
            type="textarea"
            v-model="editDoctor.recomm"
            autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">
          编辑
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.large-dept-tag {
  font-size: 14px !important;
  padding: 10px 15px !important;
  height: auto !important;
  line-height: 1.1 !important;
  border-radius: 6px !important;
  font-weight: 450 !important;
}

/* 添加圆形照片样式 */
.circular-photo {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  object-fit: cover;
  display: block;
  margin: 5px auto;
}

.large-dept-tag {
  font-size: 14px !important;
  padding: 10px 15px !important;
  height: auto !important;
  line-height: 1.1 !important;
  border-radius: 6px !important;
  font-weight: 450 !important;
}

</style>